#include "hybrid_rpc_server.hpp"
#include <iostream>
#include <thread>
#include <chrono>
#include "testjson.hpp"
#include "json_rpc_client.hpp"

using namespace std;

void rpc_client_test (JsonRpcClient &client)
{
    json result;
    auto start = std::chrono::high_resolution_clock::now ();
    json result1 = client.call ("add", {5, 3});
    auto end = std::chrono::high_resolution_clock::now ();
    std::chrono::duration<double, std::nano> elapsed = end - start;
    cout << "duration = " << elapsed.count () << endl;

    std::cout << "5 + 3 = " << result1.get<double> () << std::endl;
}

int main ()
{
    //Team team{"A Team", {Person ("Alice", 25), Person ("Bob", 30)}};
    //json j = team; // 自动处理嵌套自定义类型
    //std::cout << j.dump (2) << std::endl;

    try {
        // 启动服务器
        HybridRPCServer server ("tcp://*:5555", // RPC端口
                                "tcp://*:5556"  // STREAM端口
        );

        // 注册示例方法
        server.registerMethod ("add", [] (const json &params) {
            if (!params.is_array () || params.size () != 2) {
                throw std::invalid_argument ("需要两个参数");
            }
            return params[0].get<int> () + params[1].get<int> ();
        });

        server.registerMethod ("GetInfo", [] (const json &params) {
            return json{{"team_name", "aaaa"}};
        });

        std::cout << "Server started:\n"
                  << " - RPC at tcp://localhost:5555\n"
                  << " - STREAM at tcp://localhost:5556\n"
                  << "Press Ctrl+C to stop..." << std::endl;

        server.start ();

        //RpcClient client ("tcp://localhost:5555");
        JsonRpcClient &client = JsonRpcClient::getInstance ("tcp://localhost:5555");
        while (1) {
            rpc_client_test (client);
        }
    }
    catch (const std::exception &e) {
        std::cerr << "Error: " << e.what () << std::endl;
        return 1;
    }
    return 0;
}